<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkEmployee\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkContact\Contract\WorkContactTagPivotContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactTodo\Contract\ContactTodoContract;

/**
 * 首页.
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @Inject
     * @var WorkContactTagPivotContract
     */
    protected $workContactTagPivotService;

    /**
     * @Inject
     * @var ContactTodoContract
     */
    protected $contactTodoService;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/workEmployee/index", methods="GET")
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];
        $params['todoType'] = $this->request->input('todoType', 0); // 0:待开始，1：已完成,2：已逾期
        $params['day'] = $this->request->input('day', date('Y-m-d')); // 0:待开始，1：已完成,2：已逾期
        // 校验参数
        $this->validated($params);

        // 基础信息
        $baseInfo = $this->baseInfo($params);
        // 待办
        $todo = $this->todo($params);

        return ['baseInfo' => $baseInfo, 'todo' => $todo];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'day' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'day.required' => '日期 必传',
        ];
    }

    private function todo(array $params): array
    {
        $today = date('Y-m-d');
        $time = date('H:i');
        $todos = $this->contactTodoService->getContactTodoByEmployeeIdDay($params['employeeId'], $params['day'], ['id', 'type', 'contact_id', 'content', 'day', 'time', 'status']);
        foreach ($todos as &$item) {
            $item['overdueHours'] = '';
            $item['overdueDays'] = '';
            $contact = $this->workContactService->getWorkContactById($item['contactId'], ['name', 'avatar']);
            $item['contactName'] = $contact['name'] ?? '';
            $item['contactAvatar'] = $contact['avatar'] ? file_full_url($contact['avatar']) : '';
            $params['day'] < $today && $item['overdueDays'] = (strtotime($today) - strtotime($params['day'])) / 86400;
        }
        unset($item);
        $wait = []; // 待开始
        $finish = []; // 已完成
        $overdue = []; // 已逾期

        foreach ($todos as $key => $item) {
            if ($item['status'] === 3) {
                $finish[] = $item;
                unset($todos[$key]);
            }
        }
        $todos = array_merge($todos);
        $params['day'] > $today && $wait = $todos;
        $params['day'] < $today && $overdue = $todos;
        if ($params['day'] == $today) {
            foreach ($todos as $todo) {
                if ($todo['time'] > $time) {
                    $wait[] = $todo;
                    continue;
                }
                if ($todo['time'] < $time) {
                    if (strtotime($today . $time) - strtotime($todo['day'] . $todo['time']) < 3600) {
                        $todo['overdueMinute'] = ceil((strtotime($today . $time) - strtotime($todo['day'] . $todo['time'])) / 360);
                    }
                    $todo['overdueHours'] = ceil((strtotime($today . $time) - strtotime($todo['day'] . $todo['time'])) / 3600);
                    $overdue[] = $todo;
                }
            }
        }
        return ['wait' => $wait, 'finish' => $finish, 'overdue' => $overdue];
    }

    private function baseInfo($params): array
    {
        // 我的客户
        $baseInfo['total'] = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeTime([$params['employeeId']], date('Y-m-d', strtotime('+1 day')));
        // 昨日新增
        $baseInfo['yesterdayAdd'] = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdTime([$params['employeeId']], date('Y-m-d', strtotime('-1 day')), date('Y-m-d'));
        // 昨日流失
        $baseInfo['yesterdayLoss'] = $this->workContactEmployeeService->countWorkContactEmployeesLossByEmployeeIdTime([$params['employeeId']], date('Y-m-d', strtotime('-1 day')), date('Y-m-d'));
        return $baseInfo;
    }
}
